<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="专业名称">
      <el-input v-model="form.major_name" />
    </el-form-item>
    <el-form-item label="所属学院">
      <el-select v-model="form.department_id" @change="handleDepartmentChange">
        <el-option 
          v-for="dept in departments" 
          :key="dept.department_id" 
          :label="dept.department_name" 
          :value="dept.department_id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="下属班级数">
      <el-input v-model="form.class_number" disabled />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">确认添加</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import MajorApi from '@/api/MajorApi';

export default {
  data() {
    return {
      form: {
        major_name: '',
        department_id: '',
        department_name: '',
        class_number: 0
      },
      departments: [] // 学院数据
    };
  },
  methods: {
    async submitForm() {
      try {
        // 验证表单
        if (!this.form.major_name || !this.form.department_id) {
          this.$message.error('请填写完整信息');
          return;
        }
        
        // 添加department_name到表单数据
        const selectedDept = this.departments.find(
          dept => dept.department_id === this.form.department_id
        );
        if (selectedDept) {
          this.form.department_name = selectedDept.department_name;
        }
        
        this.$emit('submit-form', this.form);
      } catch (error) {
        console.error("表单提交错误:", error);
        this.$message.error('提交失败');
      }
    },
    closeDialog() {
      this.$emit('close-dialog');
    },
    async fetchColleges() {
      try {
        const response = await MajorApi.getCollegesForm();
        this.departments = response.data.data || response.data; // 适配不同响应格式
        console.log("学院数据:", this.departments);
      } catch (error) {
        console.error("学院信息获取错误:", error);
        this.$message.error('获取学院信息失败');
      }
    },
    handleDepartmentChange(value) {
      this.form.department_id = value;
      // 更新department_name
      const selectedDept = this.departments.find(
        dept => dept.department_id === value
      );
      if (selectedDept) {
        this.form.department_name = selectedDept.department_name;
      }
    }
  },
  created() {
    this.fetchColleges();
  }
};
</script>